package com.ja.openchat.viewmodels;

import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.databinding.ObservableField;
import androidx.databinding.ObservableInt;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.ja.openchat.R;
import com.ja.openchat.data.RegisterVue;
import com.ja.openchat.http.HttpVueClient;
import com.lzy.okgo.callback.AbsCallback;
import com.lzy.okgo.model.Response;
import com.zy.openchat.App;
import com.zy.openchat.core.manager.AuthUserManager;
import com.zy.openchat.core.manager.TelegramManager;
import com.zy.openchat.core.manager.TgEvent;
import com.zy.openchat.core.manager.TgResponse;
import com.zy.openchat.core.manager.TgResultBlock;
import com.zy.openchat.core.model.file.DocumentInfo;
import com.zy.openchat.core.model.user.UserInfo;
import com.ja.openchat.ui.MainActivity;

import org.apache.commons.lang3.StringUtils;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.Map;

import me.goldze.mvvmhabit.base.BaseViewModel;
import me.goldze.mvvmhabit.binding.command.BindingAction;
import me.goldze.mvvmhabit.binding.command.BindingCommand;
import me.goldze.mvvmhabit.binding.command.BindingConsumer;
import me.goldze.mvvmhabit.bus.Messenger;
import me.goldze.mvvmhabit.utils.KLog;

import static com.blankj.utilcode.util.StringUtils.getString;


public class SetNickNameViewModel extends BaseViewModel {
    //手机号的绑定
    public ObservableField<String> userNick = new ObservableField<>("");
    //用户名清除按钮的显示隐藏绑定
    public ObservableInt clearBtnVisibility = new ObservableInt(View.INVISIBLE);

    public ObservableField<Boolean> isFill = new ObservableField<Boolean>(false);


    public SetNickNameViewModel(@NonNull Application application) {
        super(application);
    }

    private String curUsername, curCountryCode, curPhone,userCode;

    public BindingCommand finishNameOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            finish();
        }
    });

    //清除用户名的点击事件, 逻辑从View层转换到ViewModel层
    public BindingCommand clearUserNameOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            userNick.set("");
        }
    });
    //用户名长度改变的回调事件
    public BindingCommand onTextChangeCommand = new BindingCommand<>(new BindingConsumer<String>() {
        @Override
        public void call(String s) {
            KLog.d("onTextChangeCommand==" + s);
            if (TextUtils.isEmpty(s)) {
                clearBtnVisibility.set(View.INVISIBLE);
                isFill.set(false);
            } else {
                clearBtnVisibility.set(View.VISIBLE);
                isFill.set(true);
            }
        }
    });
    //用户名输入框焦点改变的回调事件
    public BindingCommand<Boolean> onFocusChangeCommand = new BindingCommand<>(new BindingConsumer<Boolean>() {
        @Override
        public void call(Boolean hasFocus) {
            if (hasFocus && !TextUtils.isEmpty(userNick.get())) {
                clearBtnVisibility.set(View.VISIBLE);
            } else {
                clearBtnVisibility.set(View.INVISIBLE);
            }
        }
    });

    //提交按钮的点击事件
    public BindingCommand loginOnClickCommand = new BindingCommand(new BindingAction() {
        @Override
        public void call() {
            login();
        }
    });
    public String localHeadImage;

    private void login() {
        if (TextUtils.isEmpty(localHeadImage)) {
            showErrorTip(getString(R.string.upload_head_img));
            return;
        }
        File file = new File(localHeadImage);
        if (!file.exists() || !DocumentInfo.isImageFile(file.getName())) {
            showErrorTip(getString(R.string.image_format_unvalid));
            return;
        }
        if (isRegisterUserSuccess) {
            requestSetHead();
            return;
        }
        click_register();
    }

    private boolean isRegisterUserSuccess = false;

    private void click_register() {
        if (StringUtils.isEmpty(userNick.get())) {
            showWarnTip(getString(R.string.firstname_null_hint));
            return;
        }
        //lastname
        String lastName = "";
        showProgress();
        TelegramManager.getTelegramManager().registerUser(getApplication(), userNick.get(), lastName, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                if (!obj.ok) {
                    hideProgress();

                    showErrorTip(getString(R.string.register_error));
                } else {

                    HttpVueClient.getInstance().post("/v1/site/register", "DYNAMIC")
                            .params("email", curUsername)
                            .params("group", "app")
                            .params("password", "123456")
                            .params("password_repetition", "123456")
                            .params("promo_code", userCode)
                            .params("mobile", curUsername)
                            .execute(new AbsCallback() {
                                @Override
                                public Object convertResponse(okhttp3.Response response) throws Throwable {
                                    String result = response.body().string();
                                    return new Gson().fromJson(result, RegisterVue.class);
                                }

                                @Override
                                public void onError(Response response) {
                                    super.onError(response);
                                    hideProgress();
                                    showErrorTip(response.getException().getMessage());
                                }

                                @Override
                                public void onSuccess(Response response) {
                                    hideProgress();
                                    RegisterVue result = (RegisterVue) response.body();
                                    if (result != null) {

                                        if (result.getCode() == 200) {

                                            SharedPreferences.Editor editor = App.getInstanse().getSharedPreferences("config", Context.MODE_PRIVATE).edit();
                                            editor.putString("Access_token", result.getData().getAccess_token());
                                            editor.putString("userInfo", new Gson().toJson(result.getData()));

                                            editor.apply();
                                            isRegisterUserSuccess = true;
                                            requestSetHead();
                                        } else showErrorTip(result.getMessage());

                                    } else {
                                        showErrorTip("注册失败");
                                    }
                                }
                            });
                }
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getString(R.string.request_error));
            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onTgEvent(final TgEvent tg_event) {
        switch (tg_event.event) {
            case EUser_Td_Ready:

                break;
            default:
                break;
        }
    }

    private void requestSetHead() {
        if (TextUtils.isEmpty(localHeadImage)) {
            showErrorTip(getString(R.string.upload_head_img));
            return;
        }
        showProgress();
        TelegramManager.getTelegramManager().setMyPhoto(getApplication(), localHeadImage, new TgResultBlock<TgResponse>() {
            @Override
            public void onResult(Map<String, Object> request, JsonObject response, TgResponse obj) {
                hideProgress();
                if (!obj.ok) {
                    showErrorTip(getApplication().getString(R.string.avatar_upload_failed) + obj.errString);
                }
                registerSuccessEvent();
            }

            @Override
            public void onTimeout(Map<String, Object> request) {
                hideProgress();
                showErrorTip(getApplication().getString(R.string.avatar_upload_failed));
                registerSuccessEvent();
            }
        });
    }


    private void registerSuccessEvent() {
        //清理数据
        AuthUserManager.cleanDestroyFolder();
        //登录
        if (UserInfo.getUserInfo().isPasswordLoginType) {
            //更新手机号
            if (!StringUtils.isEmpty(UserInfo.getUserInfo().phone_number)) {
                AuthUserManager.getAuthUserManager().login(UserInfo.getUserInfo().phone_number, UserInfo.getUserInfo().data_directory);
            } else {
                AuthUserManager.getAuthUserManager().login(String.format("%s", curUsername), UserInfo.getUserInfo().data_directory);
            }
        } else {
            AuthUserManager.getAuthUserManager().login(String.format("%s%s", curCountryCode, curPhone), UserInfo.getUserInfo().data_directory);
        }
        //跳转主页面
        startActivity(MainActivity.class);
        Messenger.getDefault().sendNoMsg(LoginViewModel.TOKEN_LOGINVIEWMODEL_FINISH);
        Messenger.getDefault().sendNoMsg(LoginByPhoneViewModel.TOKEN_LOGINBYPHONEVIEWMODEL_FINISH);
        Messenger.getDefault().sendNoMsg(RegisterViewModel.TOKEN_REGISTERVIEWMODEL_FINISH);
        Messenger.getDefault().sendNoMsg(PhoneCodeViewModel.TOKEN_PHONECODEVIEWMODEL_FINISH);


//        ShareInstall.getInstance().reportRegister(new OnReportRegisterListener() {
//            @Override
//            public void onSuccess() {
//                Log.d("shareinstall", "reportRegister onSuccess");
//            }
//            @Override
//            public void onError() {
//                Log.d("shareinstall", "reportRegister onError");
//            }
//        });


        finish();
    }

    public void setCurUserInfo(Bundle bundle) {
        if (bundle != null) {
            curUsername = bundle.getString("curUsername");
            userCode = bundle.getString("userCode");
            curPhone = bundle.getString("curPhone");
            curCountryCode = bundle.getString("curCountryCode");
        }
    }
}
